package com.five.welcome.utils;

import com.alibaba.fastjson2.JSONObject;
import com.five.welcome.pojo.BaiduFaceRequestBody;
import com.five.welcome.pojo.FaceResult;
import lombok.Data;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Data
@Component
public class FaceDetectUtil {


    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /*也可从yml文件里获取*/
    @Value("${baidu.access_token}")
    private String ACCESS_TOKEN;

    public boolean Detect(String base64) throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        // image 可以通过 getFileContentAsBase64("C:\fakepath\dockerlogo.png") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        BaiduFaceRequestBody BaiduFaceRequestBody = new BaiduFaceRequestBody(base64, "BASE64");
        String jsonString = JSONObject.toJSONString(BaiduFaceRequestBody);
        RequestBody body = RequestBody.create(mediaType, jsonString);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + ACCESS_TOKEN)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        if (response.body() != null) {
            String string = response.body().string();
            FaceResult faceResult = JSONObject.parseObject(string, FaceResult.class);
            if (faceResult.getError_code().equals("0")) {
                return true;
            }
            return false;
        }
        return false;
    }
}
